import { ref } from 'vue'

import { QueryToString } from '@/hooks/utils'

const DEFAULT_HEADER = {
    'content-type': 'application/json'
}

const DEFAULT_OPTIONS = {
    method: 'GET',
    headers: DEFAULT_HEADER,
    data: {},
    query: {},
}

const BASE_URL = 'https://api.yalkan.com.cn'

const useRequest = (action, options = {}) => {
    const {
        method,
        headers,
        data,
        query,
    } = {
        ...DEFAULT_OPTIONS,
        ...options
    }

    const header = {
        ...DEFAULT_HEADER,
        ...headers,
    }

    if (method === 'POST') {
        header['content-type'] = 'application/x-www-form-urlencoded'
    }

    const _url = `${BASE_URL}/apiv4_0_4/yalkan/intro/${action}/1/`
    const url = method === 'POST' ? `${_url}?${QueryToString(query)}` : _url

    const isFetching = ref(false)

    const fetchData = () => {
        new Promise((resolve, reject) => {
            isFetching.value = true
            uni.request({
                url,
                header,
                data,
                method,
                success(res) {
                    resolve(res)
                },
                fail(err) {
                    reject(err)
                },
                complete() {
                    isFetching.value = false
                },
            })
        })
    }

    return {
        fetchData,
        isFetching,
    }
}

export {
    useRequest,
}